import lodash from 'lodash';
import moment from 'moment';
import path from 'path';
import appRoot from 'app-root-path';
import fs from 'fs';
import json2csv from 'json2csv';
import config from '../../../../etc';
import * as activityData from '../activity/data';
import * as institutionCore from '../../sys/institution/core';
import * as data from './data';
import log from '../../../log';
import * as util from '../../../util/index';

const likeParms = 'name'.split(',');

export function fetch(query, page, pageSize, user) {
    return util.resolve().then(() => {
        log.info('fetch policy params----', query);
        log.info('fetch policy user----', user);
        const pageOpt = {
            page,
            pageSize
        };
        let where = [];
        if (lodash.keys(query).length > 0) {
            lodash.mapKeys(query, (value, key) => {
                if (likeParms.indexOf(key) >= 0) {
                    where.push([`${key}`, 'like', `%${value}%`]);
                } else if (key === 'from') {
                    where.push(['createTime', '>=', `${value}`]);
                } else if (key === 'to') {
                    where.push(['createTime', '<=', `${value}`]);
                } else {
                    where.push([`${key}`, '=', `${value}`]);
                }
            });
        }
        //业务员只能获取创建的保单列表
        if (user.userType === 2) {
            where.push(['salesmanId', '=', user.id]);
            return data.fetch(where, 1, pageOpt).then(res => {
                log.info('fetch policy result----', res.toJSON());
                return util.data(res, 1);
            });
        }
        //机构管理员只能看本机构和所有子机构的保单列表
        if (user.userType === 3) {
            return institutionCore.getAllLevelSonIds(user.institutionId).then(r => {
                where.push(['institutionId', 'in', r]);
                return data.fetch(where, 1, pageOpt).then(res => {
                    log.info('fetch policy result----', res.toJSON());
                    return util.data(res, 1);
                });
            });
        }
        if (where.length < 1) {
            where = null;
        }
        return data.fetch(where, 1, pageOpt).then(res => {
            log.info('fetch policy result----', res.toJSON());
            return util.data(res, 1);
        });
    }).catch(err => {
        log.error('fetch policy is err----', err);
        return err;
    });
}

export function find(query, user) {
    return util.resolve().then(() => {
        log.info('find policy params----', query);
        log.info('find policy user----', user);
        let where = [];
        if (lodash.keys(query).length > 0) {
            lodash.mapKeys(query, (value, key) => {
                if (likeParms.indexOf(key) >= 0) {
                    where.push([`${key}`, 'like', `%${value}%`]);
                } else if (key === 'from') {
                    where.push(['createTime', '>=', `${value}`]);
                } else if (key === 'to') {
                    where.push(['createTime', '<=', `${value}`]);
                } else {
                    where.push([`${key}`, '=', `${value}`]);
                }
            });
        }
        //业务员只能获取自己创建的保单列表
        if (user.userType === 2) {
            where.push(['salesmanId', '=', user.id]);
            return data.find(where, 1).then(res => {
                log.info('find policy result----', util.data(res));
                return util.data(res);
            });
        }
        //机构管理员只能看本机构和所有子机构的保单列表
        if (user.userType === 3) {
            return institutionCore.getAllLevelSonIds(user.institutionId).then(r => {
                where.push(['institutionId', 'in', r]);
                return data.find(where, 1).then(res => {
                    log.info('fetch policy result----', res.toJSON());
                    return util.data(res, 1);
                });
            });
        }
        if (where.length < 1) {
            where = null;
        }
        return data.find(where, 1).then(res => {
            log.info('find policy result----', util.data(res));
            return util.data(res);
        });
    }).catch(err => {
        log.error('find policy is err----', err);
        return err;
    });
}

export function add(policys = [], user) {
    return util.resolve().then(() => {
        log.info('add policy params----', JSON.stringify(policys));
        log.info('add policy user----', JSON.stringify(user));
        if (policys.length === 0) {
            throw '提交的保单数据为空';
        }
        return activityData.find([{id: policys[0].activityId}], 0).then(res => {
            res = res.toJSON() || [];
            const activity = res[0];
            log.info('activity:', activity);
            delete activity.images;
            delete activity.institution;
            delete activity.policyCount;
            delete activity.completedMoney;
            delete activity.activityCustomerCount;
            delete activity.myCustomerCount;
            if (res.length === 0) {
                throw '活动不存在';
            }
            //判断业务员是否有提交保单权限
            return institutionCore.getAllLevelPids(user.institutionId).then(r => {
                if (user.userType === 2) {
                    if (!lodash.includes(r, activity.institutionId)) {
                        throw '您没有权限参与此活动';
                    }
                }
                if (moment(activity.dateEnd) < moment()) {
                    throw '活动已过期，不能提交保单';
                }
                if (moment(activity.dateStart) > moment()) {
                    throw '活动还未开始，不能提交保单';
                }
                const policy = [];
                policys.forEach(i => {
                    if (i.money < 0) {
                        throw '保单金额不能小于零';
                    }
                    i.id = util.uuid();
                    i.status = '1';
                    i.institutionId = user.institutionId;
                    i.salesmanId = user.id;
                    policy.push(i);
                    //修改活动已认购金额
                    //activity.completedMoney += i.money;
                });
                return data.add(policy, activity).then(() => {
                    log.info('add policy result----', JSON.stringify(policy));
                    return policy;
                });
            });
        });
    }).catch(err => {
        log.error('add policy is err----', err);
        throw err;
    });
}

export function edit(policy) {
    return util.resolve().then(() => {
        log.info('edit policy params----', policy);
        if (policy.money < 0) {
            throw '保单金额不能小于零';
        }
        return activityData.find([{id: policy.activityId}], 0).then(res => {
            res = res.toJSON() || [];
            if (res.length === 0) {
                throw '活动不存在';
            }
            const activity = res[0];
            delete activity.images;
            delete activity.institution;
            delete activity.policyCount;
            delete activity.completedMoney;
            delete activity.activityCustomerCount;
            delete activity.myCustomerCount;
            return data.find([{id: policy.id}], 0).then(r => {
                //减去旧的保单金额
                r = r.toJSON() || [];
                if (r.length === 0) {
                    throw '要修改保单不存在';
                }
                activity.complatedMoney -= r.money;
                //加上新的保单金额
                activity.complatedMoney += policy.money;
                return data.edit(policy, activity).then(() => {
                    log.info('edit policy result----', JSON.stringify(policy));
                    return policy;
                });
            });
        });
    }).catch(err => {
        log.error('edit policy is err----', err);
        return err;
    });
}

export function del(id) {
    return util.resolve().then(() => {
        log.info('delete policy params----', id);
        return data.find([{id}], 0).then(r => {
            r = r.toJSON() || [];
            if (r.length === 0) {
                throw '保单不存在';
            }
            const policy = r[0];
            return activityData.find([{id: policy.activityId}], 0).then(res => {
                res = res.toJSON() || [];
                if (res.length === 0) {
                    throw '活动不存在';
                }
                const activity = res[0];
                activity.complatedMoney -= policy.money;
                return data.del(id, activity).then(res => {
                    log.info('delete policy result----success', util.data(res));
                    return util.data(res);
                });
            });
        });
    }).catch(err => {
        log.error('delete policy is err----', err);
        return err;
    });
}

/**
* 生成csv文件
 */
function createCsv(data) {
    return util.resolve().then(() => {
        const nowStr = moment().format('YYYYMMDDHHmmss');
        const newFilenName = `保单数据导出_${nowStr}_${util.randomDigits(4)}.csv`;
        const url = path.join(config.policyCsvExportDir, newFilenName);
        const destFilePath = path.join(appRoot.toString(), url).toString();
        log.info('csv存储path:', destFilePath);

        const fields = [
            {
                label: '客户姓名',
                value: 'customName',
                default: ''
            },
            {
                label: '客户手机号',
                value: 'customMobile',
                default: ''
            },
            {
                label: '客户身份证号',
                value: 'customIDCard',
                default: ''
            },
            {
                label: '认购码',
                value: 'code',
                default: ''
            },
            {
                label: '意向金额',
                value: 'money',
                default: '0.00'
            },
            {
                label: '提交时间',
                value: (row) => {
                    return moment(row.createTime).format('YYYY-MM-DD HH:mm:ss');
                },
                default: ''
            },
            {
                label: '活动名称',
                value: 'activity.name',
                default: ''
            },
            {
                label: '活动所属机构',
                value: 'activity.institution.name',
                default: ''
            },
            {
                label: '业务员姓名',
                value: 'salesman.name',
                default: ''
            },
            {
                label: '业务员工号',
                value: 'salesman.code',
                default: ''
            },
            {
                label: '业务员手机号',
                value: 'salesman.mobile',
                default: ''
            },
            {
                label: '业务员所属机构',
                value: 'salesman.institution.name',
                default: ''
            },
        ];
        log.info('exportCsv policy fields:', fields);
        return new Promise((resolve, reject) => {
            if (data.length === 0) {
                reject('没有数据');
            }
            return json2csv({data, fields, excelStrings: true}, (err, csv) => {
                //将json转为csv格式的buf
                //在写文件之前，转一下编码
                const buf = Buffer.concat([new Buffer('\xEF\xBB\xBF', 'binary'), new Buffer(csv)]);
                return resolve(new Promise((resolve, reject) => {
                    return fs.writeFile(destFilePath, buf, (err) => {
                        if (err) {
                            log.error('exportCsv policy is err----', err);
                            reject(err);
                        }
                        log.info('exportCsv create file:', destFilePath);
                        resolve(destFilePath);
                    });
                }).then(() => {
                    return {url};
                }));
            });
        });
    }).catch(err => {
        log.error('exportCsv policy is err----', err);
        return err;
    });
}

export function exportCsv(query, user) {
    return util.resolve().then(() => {
        log.info('exportCsv policy params----', query);
        log.info('exportCsv policy user----', user);

        let where = [];
        if (lodash.keys(query).length > 0) {
            lodash.mapKeys(query, (value, key) => {
                if (likeParms.indexOf(key) >= 0) {
                    where.push([`${key}`, 'like', `%${value}%`]);
                } else if (key === 'from') {
                    where.push(['createTime', '>=', `${value}`]);
                } else if (key === 'to') {
                    where.push(['createTime', '<=', `${value}`]);
                } else {
                    where.push([`${key}`, '=', `${value}`]);
                }
            });
        }
        //业务员只能获取自己创建的保单列表
        if (user.userType === 2) {
            where.push(['salesmanId', '=', user.id]);
            return data.find(where, 1).then(res => {
                res = util.data(res);
                return createCsv(res);
            });
        }
        //机构管理员只能看本机构和所有子机构的保单列表
        if (user.userType === 3) {
            return institutionCore.getAllLevelSonIds(user.institutionId).then(r => {
                where.push(['institutionId', 'in', r]);
                return data.find(where, 1).then(res => {
                    res = util.data(res);
                    return createCsv(res);
                });
            });
        }
        if (where.length < 1) {
            where = null;
        }
        return data.find(where, 1).then(r => {
            r = util.data(r);
            return createCsv(r);
        });
    }).catch(err => {
        log.error('exportCsv policy is err----', err);
        return err;
    });
}
